<script setup lang="ts">
import { reactive, ref } from "vue";
import { RoleRule } from "@/view/Role/utils/rules.ts";
import { ElMessage } from "element-plus";
import { postRoleAPI, putRoleAPI } from "@/api/user.ts";

const type = ref(0)
const id = ref('')
const ruleFormRef = ref()
const dialogVisible = ref(false)
const form = reactive({
  name: ''
})
const emit = defineEmits(['get'])

const init = (row: any, number: number) => {
  type.value = number
  dialogVisible.value = true
  id.value = ''
  form.name = ''
  if (number) {
    form.name = row.name
    id.value = row._id
  }
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
}

// 添加
const handleAdd = async () => {
  const res = await postRoleAPI(form)
  ElMessage({
    type: res.code === 0 ? 'success' : 'error',
    message: res.message
  })
  emit('get')
  handleCancel()
}

// 编辑
const handleEdit = async () => {
  const res = await putRoleAPI(id.value, form)
  ElMessage({
    type: res.code === 0 ? 'success' : 'error',
    message: res.message
  })
  emit('get')
  handleCancel()
}

defineExpose({
  init
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="type === 0 ? '添加角色' : '编辑角色'" width="40%">
    <el-form ref="ruleFormRef"
             :rules="RoleRule"
             :model="form">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="type === 0" type="primary" @click="handleAdd">提交</el-button>
      <el-button v-else type="primary" @click="handleEdit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
